/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.txt.access.capability.libraries.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author seccia
 */
public class CapabilityConnection {

    protected static final Logger LOGGER = Logger.getLogger(CapabilityConnection.class.getName());
    private CapabilityConnectioProps props;
    private Connection rabbitConnection;
    private ConnectionFactory factory;
    private Channel rabbitChannel;
    private boolean isConnetcted;

    public CapabilityConnection(CapabilityConnectioProps props) {
        this.props = props;
    }

    protected synchronized void newConnection() throws IOException {

        LOGGER.info("Creating RabbitMQ Guest ConnectionFactory...");
        LOGGER.log(Level.INFO, "Using User Name: {0}", props.getUsername());
        LOGGER.log(Level.INFO, "Using User Pwd: {0}", props.getAccessToken());
        LOGGER.log(Level.INFO, "Using Broker Host: {0}", props.getBrokerHost());
        LOGGER.log(Level.INFO, "Using Broker Port: {0}", props.getBrokerPort());
        LOGGER.log(Level.INFO, "Using Broker V Hosh: {0}", props.getBrokerVHost());
        LOGGER.log(Level.INFO, "Using Request Queue: {0}", props.getQueueName());

        factory = new ConnectionFactory();
        factory.setVirtualHost(props.getBrokerVHost());
        factory.setPassword(props.getAccessToken());
        factory.setUsername(props.getUsername());
        factory.setPort(props.getBrokerPort());
        factory.setHost(props.getBrokerHost());
        LOGGER.info("Creating RabbitMQ Connection...");
        rabbitConnection = factory.newConnection();
        LOGGER.info("Creating RabbitMQ Channel...");
        rabbitChannel = rabbitConnection.createChannel();
    }

    public synchronized void disconnect() throws IOException{
        LOGGER.info("Closing RabbitMQ channel...");
        if (rabbitChannel != null && rabbitChannel.isOpen()) {
            rabbitChannel.close();
        }
        LOGGER.info("Closing RabbitMQ connection...");
        if (rabbitConnection != null && rabbitConnection.isOpen()) {
            rabbitConnection.close();
        }
    }

    public synchronized boolean isConnected() {
        return isConnetcted;
    }

    public synchronized String getQueueName(){
        return this.props.getQueueName();
    }

    public synchronized Channel getChannel() {
        return rabbitChannel;
    }
}
